package com.example.skudemo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
 * 自定义自动生成代码的
 */
public class GeneratorCode {
    private final static String DB_USERNAME = "root";
    private final static String DB_HOST = "localhost";
    private final static String DB_PORT = "3306";
    private final static String DB_PASSWORD = "123456";
    private final static String DB_DATABASE = "sku_demo";
    private final static String PROJECT_PATH = "com/example/skudemo";

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setAuthor("水痕")
                .setOpen(false)
                .setFileOverride(false)
                .setIdType(IdType.AUTO)
                //实体属性 Swagger2 注解
                .setSwagger2(false)
                .setBaseResultMap(true)
                .setEntityName("%sEntity")
                .setControllerName("%sController");
        mpg.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://" + DB_HOST + ":" + DB_PORT + "/" + DB_DATABASE + "?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(DB_USERNAME);
        dsc.setPassword(DB_PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(PROJECT_PATH.replace("/", "."))
                .setPathInfo(getPathInfo())
                .setController("controller")
                .setEntity("model")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl")
                .setXml("xml");
        mpg.setPackageInfo(pc);

        // 模板配置
//        TemplateConfig templateConfig = new TemplateConfig();
//        templateConfig.setXml(null);
//        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setSuperEntityClass(PROJECT_PATH.replace("/", ".") + ".model.BaseEntity")
                .setEntityLombokModel(true)
                .setRestControllerStyle(true)
                // 抽取公共字段
                .setSuperEntityColumns("id", "created_at", "updated_at", "deleted_at")
                .setEntitySerialVersionUID(false)
                .setEntityLombokModel(true)
                .setInclude(scanner("表名，多个英文逗号分割").split(","))
                .setControllerMappingHyphenStyle(true)
                .setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 用户输入
     *
     * @param tip
     * @return
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 配置生成路径
     *
     * @return
     */
    private static Map<String, String> getPathInfo() {
        Map<String, String> pathInfo = new HashMap<>();
        String path = "/src/main/java/" + PROJECT_PATH;
        pathInfo.put(ConstVal.ENTITY_PATH, System.getProperty("user.dir") + path + "/model");
        pathInfo.put(ConstVal.MAPPER_PATH, System.getProperty("user.dir") + path + "/mapper");
        pathInfo.put(ConstVal.SERVICE_PATH, System.getProperty("user.dir") + path + "/service");
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH, System.getProperty("user.dir") + path + "/service/impl");
        pathInfo.put(ConstVal.CONTROLLER_PATH, System.getProperty("user.dir") + path + "/controller");
        pathInfo.put(ConstVal.XML_PATH, System.getProperty("user.dir") + "/src/main/resources/mapper");
        return pathInfo;
    }
}